package org.example.auth.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.example.auth.dao.LimiterCountDao;
import org.example.auth.domain.entity.LimiterCountEntity;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQListener {
    @Autowired
    private LimiterCountDao limiterCountDao;

    /**
     * 统计网关限流信息
     * @param message 接收到的消息
     */
    @RabbitListener(queues = "item_queue")
    public void listenLimiter(String message){
        JSONObject limiterDataObject = JSONObject.parseObject(message);
        // 计算时间
        String timeStr = (String) limiterDataObject.get("time");
        String minute = StringUtils.substring(timeStr, 14, 16);
        Integer saveMinute = ((Integer)(Integer.parseInt(minute) / 5))*5;
        String saveTimeStr = StringUtils.left(timeStr, 14) + saveMinute + ":00";
        QueryWrapper<LimiterCountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("time", saveTimeStr)
                .eq("token", limiterDataObject.get("token"));
        LimiterCountEntity existLimiterCount = limiterCountDao.selectOne(queryWrapper);
        if (existLimiterCount == null) { // 如果没有查找到数据
            // 新增数据
            LimiterCountEntity newLimiterCount = new LimiterCountEntity();
            newLimiterCount.setTime(saveTimeStr);
            newLimiterCount.setToken((String) limiterDataObject.get("token"));
            if ((Integer) limiterDataObject.get("isPass") == 1) {
                newLimiterCount.setPassCount(1L);
                newLimiterCount.setRefuseCount(0L);
            } else {
                newLimiterCount.setPassCount(0L);
                newLimiterCount.setRefuseCount(1L);
            }
            newLimiterCount.setTotalCount(1L);
            limiterCountDao.insert(newLimiterCount);
        } else { // 如果查到数据了
            // 更新数据
            if ((Integer) limiterDataObject.get("isPass") == 1) {
                existLimiterCount.setPassCount(existLimiterCount.getPassCount()+1);
            } else {
                existLimiterCount.setRefuseCount(existLimiterCount.getRefuseCount()+1);
            }
            existLimiterCount.setTotalCount(existLimiterCount.getTotalCount()+1);
            limiterCountDao.updateById(existLimiterCount);
        }
    }
}
